<template>
  <div>
    <SearchContainer @search="searchData" @reset="() => formRef.resetFields()">
      <a-form ref="formRef" class="form-style-flex" :model="formState" :label-col="{ style: { width: '80px' } }">
        <a-form-item label="" name="zjm">
          <a-input v-model:value="formState.zjm" class="w-64" placeholder="销售单号/姓名/助记码/信息卡号" />
        </a-form-item>
        <a-form-item label="配镜时间" name="dateRange">
          <a-range-picker v-model:value="formState.dateRange" class="w-64" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
        </a-form-item>
        <a-form-item label="" name="status" class="w-1/4 ml-10">
          <a-radio-group v-model:value="formState.status" @change="onChangeStatus">
            <a-radio>全部</a-radio>
            <a-radio :value="0">未取镜</a-radio>
            <a-radio :value="1">已取镜</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </SearchContainer>
    <a-card class="mt-2">
      <div class="flex justify-start">
        <a-button class="mb-2" @click="onAdd"> 导出 </a-button>
        <a-button type="primary" :disabled="selectedRowKeys.length <= 0" :loading="batchLoaing" class="mb-2 ml-2" @click="onBatchTake()"> 一键取镜 </a-button>
      </div>
      <BaseTable
        :data-source="dataSource"
        fill
        row-key="id"
        :loading="loading"
        :scroll="{ x: 2700 }"
        column-code="000244"
        :row-selection="{
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange,
          getCheckboxProps: (record) => ({
            disabled: record.takerStatus === '1'
          })
        }"
        :pagination="{ total: page.total, current: page.current, pageSize: page.pageSize }"
        @change="onPageChange"
      >
        <template #bodyCell="{ column, index, record }">
          <template v-if="column.dataIndex === 'xh'">
            {{ index + 1 }}
          </template>
          <template v-if="column.dataIndex === 'takerStatus'">
            <a-tag v-if="record.takerStatus === '1'" color="green">已取镜</a-tag>
            <a-tag v-else color="red">未取镜</a-tag>
          </template>
          <template v-if="column.dataIndex === 'payStatus'">
            <a-tag v-if="record.payStatus === '已缴费'" color="green">{{ record.payStatus }}</a-tag>
            <a-tag v-else color="red">{{ record.payStatus }}</a-tag>
          </template>
          <template v-if="column.dataIndex === 'id'">
            <PopoverTable :config="detailConfig" :params="{ id: record.id }" :width="1100">
              <template #bodyCell="{ column: popColumn, record: popRecord }">
                <template v-if="popColumn.dataIndex === 'payItemName'">
                  <MedicineInfo :value="{ mc: popRecord.payItemName, gg: popRecord.specification, cj: popRecord.cj }" />
                </template>
                <template v-if="popColumn.dataIndex === 'isOutside'">
                  <span v-if="popRecord.isOutside == 1">是</span>
                  <span v-else>否</span>
                </template>
                <template v-if="popColumn.dataIndex === 'num'">
                  <span>{{ popRecord.num }}</span
                  ><span class="text-gray-400 ml-2 text-xs">{{ popRecord.unit }}</span>
                </template>
              </template>
              {{ record.id }}
            </PopoverTable>
          </template>
          <template v-if="column.dataIndex === 'action'">
            <a-space>
              <BaseButton confirm-text="请确认取镜?" type="link" :disabled="record.takerStatus === '1'" size="small" @click="onTake(record)"> 取镜 </BaseButton>
              <!-- :disabled="record.payStatus === '未缴费'" -->
            </a-space>
          </template>
        </template>
      </BaseTable>
    </a-card>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import dayjs from 'dayjs'
import { message } from 'ant-design-vue'
import { post } from '@/utils/request'
// import useUserStore from '@/store/user'

// const { empName } = useUserStore()
const rowData = ref(null)
const formRef = ref(null)
const dataSource = ref([])

const open = ref(true)
const loading = ref(false)
const selectedRowKeys = ref([])

const formState = ref({
  dateRange: [dayjs(new Date().setDate(new Date().getDate() - 2)).format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')],
  zjm: '',
  status: 0
})
const detailConfig = ref({
  url: '/optometry/ooadolescentcheck/GetOoOpticianSubrecordeList',
  columnCode: '000245',
  rowKey: 'id',
  formatResult: (data) => {
    return data.map((item, index) => ({
      ...item,
      xh: index + 1
    }))
  }
})
const page = ref({
  total: 0,
  current: 1,
  pageSize: getSystemConfig('DFFAULT_PAGE_SHOW_COUNT') || 10
})
const searchData = () => {
  page.value.current = 1
  getDataSource()
}
const onTake = async (record) => {
  const { code, msg } = await post('/optometry/ooadolescentcheck/doTakeGlasses', {
    id: record.id,
    takerStatus: '1',
    payStatus: record.payStatus
  })
  if (code !== 0) return message.error(msg || '操作失败')
  getDataSource()
  message.success(msg)
}
const batchLoaing = ref(false)
const onBatchTake = async () => {
  if (selectedRowKeys.value.length <= 0) return message.warning('请至少选择一条数据')
  const params = []
  dataSource.value.forEach((item) => {
    if (selectedRowKeys.value.indexOf(item.id) > -1) {
      params.push({
        id: item.id,
        takerStatus: '1',
        payStatus: item.payStatus
      })
    }
  })
  batchLoaing.value = true
  const { code, msg } = await post('/optometry/ooadolescentcheck/doTakeGlassesList', params)
  batchLoaing.value = false
  if (code !== 0) return message.error(msg || '操作失败')
  getDataSource()
  message.success(msg)
}
const onAdd = () => {
  rowData.value = null
  open.value = true
}
const getDataSource = async () => {
  loading.value = true
  const { data, code, total } = await post('/optometry/ooadolescentcheck/getOpticianRecordList', {
    ...formState.value,
    pageNum: page.value.current,
    pageSize: page.value.pageSize,
    stdate: formState.value.dateRange?.[0],
    eddate: formState.value.dateRange?.[1]
  })
  loading.value = false
  if (code === 0) {
    dataSource.value = data
    page.value.total = total
    if (dataSource.value.length > 0) {
      selectedRowKeys.value = dataSource.value.map((item) => {
        if (item.takerStatus !== '1') return item.id
      })
    }
  }
}
const onChangeStatus = () => {
  searchData()
}
const onPageChange = ({ current, pageSize }) => {
  page.value.current = current
  page.value.pageSize = pageSize
  getDataSource()
}
const onSelectChange = (keys) => {
  selectedRowKeys.value = keys
}

onMounted(() => {
  getDataSource()
})
</script>
